<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { store } from '@/store';
import API from '@/services';
import { IconInfoCircle } from '@arco-design/web-vue/es/icon';
import { bindType } from '@/hooks/base';

const {
  metrics: { getMetricsUndevelop_status_metrics },
  dataTable: { getDataTableGetDimensionIdAndName },
  enumBao: { getSceneTimeperiodType },
  scene: { getSceneColumnDetail, getSceneGet_column_info }
} = API;
const querytableRef = ref<any>(null);
const tableContainer = ref<any>(null);
const columns: any[] = [
  {
    title: '字段名',
    dataIndex: 'name',
    width: 100
  },
  {
    title: '字段类型',
    dataIndex: 'dataType',
    width: 100
  },
  {
    title: '描述',
    width: 100,
    slotName: 'comment'
  },
  {
    title: '绑定指标/维度/统计粒度',
    width: 290,
    slotName: 'columnType'
  },
  {
    title: '组件类型',
    width: 100,
    slotName: 'logicDataType',
    titleSlotName: 'logicDataTypeTitle'
  }
];
const bindContList = [
  {
    label: '指标',
    value: bindType.METRICS
  },
  {
    label: '维度',
    value: bindType.DIMENSION
  },
  {
    label: '统计粒度',
    value: bindType.TIMEPERIOD
  }
];
const bindContIndex = ref(-1);
const metricsList = ref<defs.OptionVO[]>([]);
const dimensionList = ref<defs.OptionVO[]>([]);
const timePeriodList = ref<defs.OptionVO[]>([]);
const componentTypeList = [
  {
    label: '数值',
    value: 'NUMERICAL'
  },
  {
    label: '日期',
    value: 'DATE'
  },
  {
    label: '文本',
    value: 'TEXT'
  }
];
const rowSelection: any = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false
});

const sceneId = computed(() => store.state.scenesManage.sceneId);
const useTableId = computed(() => store.state.scenesManage.step1UseTableId);
const selectedTable = computed(
  () => store.state.scenesManage.selectedTableStep3
);
const tableData = ref<any>([]);
const pagination = reactive({ pageSize: 10, currentPage: 1 });
const selectedKeys = ref<any>([]);
const selectionList = ref<any>([]);
const busy = ref(false);
const tableLoading = ref(false);
const isMore = ref(false);

// 请求表格数据
const fetchTableList = async () => {
  tableLoading.value = true;
  let params = {
    tableId: useTableId.value,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  };
  const res = await getSceneColumnDetail(params);
  if (res.code === 200) {
    tableData.value = tableData.value.concat(res.data);
    if (!res.data?.length) {
      busy.value = true;
    } else {
      busy.value = false;
    }
    if (res.data?.length === 10) {
      isMore.value = true;
    } else {
      isMore.value = false;
    }
    processTableData(tableData.value);
    tableLoading.value = false;
  } else {
    tableLoading.value = false;
  }
};

// 获取未加工指标数据
const fetchMetricsList = () => {
  getMetricsUndevelop_status_metrics({}).then((res: any) => {
    if (res.code === 200) {
      metricsList.value = res.data;
    }
  });
};

// 获取下拉统计粒度
const fetchTimePeriodList = () => {
  getSceneTimeperiodType().then((res: any) => {
    if (res.code === 200) {
      timePeriodList.value = res.data;
    }
  });
};

// 获取维度
const fetchDimensionList = () => {
  getDataTableGetDimensionIdAndName({}).then((res: any) => {
    if (res.code === 200) {
      dimensionList.value = res.data;
    }
  });
};

// 存储当前的数据
const saveData = () => {
  processTable(selectedKeys.value);
  store.commit('scenesManage/saveFormStep3Data', selectionList.value);
};

// 切换绑定的指标/维度/统计维度
const changeBindCont = (record: any, index: number) => {
  bindContIndex.value = index;
  record.bindId = '';
};

// 选择表格
const selectionChange = (val: any) => {
  selectionList.value = [];
  selectedKeys.value = [...new Set(val)];
  store.commit('scenesManage/resetFormStep3');
  store.commit('scenesManage/saveSelectedTableStep3', val);
};

// 根据keys找到表格对应行
const processTable = (keyList: any) => {
  tableData.value.forEach((row: any) => {
    if (keyList.some((item: any) => item === row.id)) {
      row.isCheck = 1;
      selectionList.value.push(row);
    }
  });
  let obj = {};
  selectionList.value = selectionList.value.reduce((cur: any, next: any) => {
    obj[next.id] ? '' : (obj[next.id] = true && cur.push(next));
    return cur;
  }, []);
};

// 获取表格反显数据
const getReverseData = () => {
  tableLoading.value = true;
  let params = {
    id: sceneId.value,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    tableSource: useTableId.value
  };
  getSceneGet_column_info({ ...params })
    .then((res: any) => {
      if (res.code === 200) {
        tableData.value = tableData.value.concat(res.data);
        if (!res.data?.length) {
          busy.value = true;
        } else {
          busy.value = false;
        }
        if (res.data?.length === 10) {
          isMore.value = true;
        } else {
          isMore.value = false;
        }
        tableLoading.value = false;
      } else {
        tableLoading.value = false;
      }
      let arrKeys: any[] = [];
      tableData.value.forEach((item: any) => {
        if (item.bindId) {
          item.bindId = String(item.bindId);
        }
        if (item.isCheck == 1) {
          arrKeys.push(item.id);
        }
      });
      arrKeys = arrKeys.concat(selectedTable.value);
      selectionChange(arrKeys);
    })
    .catch(() => {
      tableLoading.value = false;
    });
};

const loadMore = () => {
  busy.value = true;
  pagination.currentPage += 1;
  if (sceneId.value) {
    getReverseData();
  } else {
    fetchTableList();
  }
};

// 处理表格数据（用于回显维度/指标）
const processTableData = (data: any) => {
  data.forEach((item: any) => {
    if (item.columnType === bindType.DIMENSION && item.matchDimensionVO) {
      item.bindId = String(item.matchDimensionVO.id);
    }
    if (item.columnType === bindType.METRICS && item.matchSimpleMetricsVO) {
      item.bindId = String(item.matchSimpleMetricsVO.id);
    }
  });
};

defineExpose({ saveData, getReverseData });

onMounted(() => {
  fetchMetricsList();
  fetchDimensionList();
  fetchTimePeriodList();
  if (sceneId.value) {
    getReverseData();
  } else {
    fetchTableList();
  }
});
</script>

<template>
  <div class="tablecontainer" ref="tableContainer">
    <a-table
      :columns="columns"
      :data="tableData"
      :row-selection="rowSelection"
      row-key="id"
      @selection-change="selectionChange"
      ref="querytableRef"
      :pagination="false"
      class="m-18 scense_table"
      v-model:selectedKeys="selectedKeys"
      :loading="tableLoading"
      :bordered="false"
      style="margin-bottom: 0"
    >
      <template #comment="{ record }">
        <a-tooltip :content="record.comment">
          <span class="field-desc">{{ record.comment }}</span>
        </a-tooltip>
      </template>

      <template #columnType="{ record, index }">
        <a-select
          placeholder="请选择"
          style="width: 100px; margin-right: 6px"
          v-model="record.columnType"
          @change="changeBindCont(record, index)"
        >
          <template #arrow-icon>
            <IconDown class="arco-select-arrow-icon" />
          </template>
          <a-option
            v-for="item of bindContList"
            :value="item.value"
            :label="item.label"
            :key="item.value"
          />
        </a-select>

        <a-select
          style="width: 150px"
          placeholder="请选择"
          v-model="record.bindId"
          allow-search
          v-if="record.columnType === bindType.METRICS"
        >
          <template #arrow-icon>
            <IconDown class="arco-select-arrow-icon" />
          </template>
          <a-option
            v-for="item of metricsList"
            :value="item.value"
            :label="item.label"
            :key="item.value"
          />
        </a-select>
        <a-select
          style="width: 150px"
          placeholder="请选择"
          v-model="record.bindId"
          allow-search
          v-if="record.columnType === bindType.DIMENSION"
        >
          <template #arrow-icon>
            <IconDown class="arco-select-arrow-icon" />
          </template>
          <a-option
            v-for="item of dimensionList"
            :value="item.value"
            :label="item.label"
            :key="item.value"
          />
        </a-select>
        <a-select
          style="width: 150px"
          placeholder="请选择"
          v-model="record.bindId"
          allow-search
          v-if="record.columnType === bindType.TIMEPERIOD"
        >
          <template #arrow-icon>
            <IconDown class="arco-select-arrow-icon" />
          </template>
          <a-option
            v-for="item of timePeriodList"
            :value="item.value"
            :label="item.label"
            :key="item.value"
          />
        </a-select>
      </template>

      <template #logicDataType="{ record }">
        <a-select
          :style="{ width: '90px' }"
          placeholder="请选择"
          v-model="record.logicDataType"
        >
          <template #arrow-icon>
            <IconDown class="arco-select-arrow-icon" />
          </template>
          <a-option
            v-for="item of componentTypeList"
            :value="item.value"
            :label="item.label"
            :key="item.value"
          />
        </a-select>
      </template>

      <template #logicDataTypeTitle>
        <span style="padding-right: 4px">组件类型</span>
        <a-tooltip
          content="应用于取数中条件筛选展示的组件，系统会根据字段类型默认匹配组件，可根据需要修改"
          :content-style="{ width: '260px' }"
          position="br"
        >
          <icon-info-circle></icon-info-circle>
        </a-tooltip>
      </template>

      <template #footer>
        <div
          style="
            width: 100%;
            font-size: 14px;
            color: #60646f;
            text-align: center;
            cursor: pointer;
          "
          v-show="isMore"
          @click="loadMore"
        >
          加载更多...
        </div>
      </template>
    </a-table>
  </div>
</template>

<style lang="scss" scoped>
.tablecontainer {
  box-sizing: border-box;
  min-height: 400px;
  flex: 1;
  ::v-deep(.arco-table) {
    .arco-table-footer {
      padding-bottom: 4px;
      padding-top: 22px;
    }
    .arco-table-cell {
      padding: 12px 18px;
    }
  }
}
.table-bind {
  .field-desc {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 120px;
    display: block;
  }
}
</style>
